package JavaSE.StreamLearning.BufferIOStream;

import java.io.*;

/**
 * 使用字节缓冲流复制字节时，读取和写入的个数不相等
 * 读取过程并不是直接从硬盘读入到内存
 * 而是 硬盘-->端口-->内存
 * 通过读入缓冲区大小的数据到端口，但是端口每次只运输一个数据到内存中
 * 最后必须通过close()或flush()方法将缓冲区的数据冲到内存中
 */

public class BufferedSingle {
    public static void main(String[] args) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(
                new FileInputStream("src\\JavaSE.StreamLearning.BufferIOStream\\a.txt"));
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream("src\\JavaSE.StreamLearning.BufferIOStream\\b.txt"));
        // 数组读写
        IOByArray(bis, bos);
        System.out.println("--------------------------------------");
        // 字节读写
        IOByByte(bis, bos);
        bis.close();
        bos.close();
    }

    private static void IOByByte(BufferedInputStream bis, BufferedOutputStream bos) throws IOException {
        int readData;
        long start = System.currentTimeMillis();
        while((readData = bis.read()) != -1) {
            bos.write(readData);
        }
        long end = System.currentTimeMillis();
        System.out.println("字节读写耗时：" + (end - start));
    }

    private static void IOByArray(BufferedInputStream bis, BufferedOutputStream bos) throws IOException {
        byte[] bytes = new byte[2048];
        int readCount;
        long start = System.currentTimeMillis();
        while((readCount = bis.read(bytes)) != -1) {
            bos.write(bytes,0,readCount);
        }
        long end = System.currentTimeMillis();
        System.out.println("数组读写耗时：" + (end - start));
    }
}
